package com.why.biyesheji.service.impl;

import com.google.common.collect.Lists;
import com.why.biyesheji.common.Constants;
import com.why.biyesheji.common.ServiceResultEnum;
import com.why.biyesheji.dao.CartMapper;
import com.why.biyesheji.dao.ProductMapper;
import com.why.biyesheji.pojo.Cart;
import com.why.biyesheji.pojo.Product;
import com.why.biyesheji.service.ICartService;
import com.why.biyesheji.util.BigDecimalUtil;
import com.why.biyesheji.util.PropertiesUtil;
import com.why.biyesheji.util.Result;
import com.why.biyesheji.util.ResultGenerator;
import com.why.biyesheji.vo.CartListVO;
import com.why.biyesheji.vo.CartProductVO;
import com.why.biyesheji.vo.MallUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by 华耀 王 on 2020/12/22
 **/
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 查询购物车列表
     * @param userId
     * @return
     */
    @Override
    public CartListVO cartList(Integer userId) {
        List<Cart> cartList = cartMapper.selectListByUserId(userId);

        List<CartProductVO> cartProductVOList = Lists.newArrayList(); //  guava的源码，其实和new 的结果是一样的。只不过写法简单，不用考虑泛型。里面有泛型的封装

        CartListVO cartListVO = new CartListVO();
        BigDecimal tempProductTotalPrice = BigDecimal.ZERO;
//        不仅可以判断获取的List是否为null，还能判断获取的List的size是否为0
        if (!CollectionUtils.isEmpty(cartList)) {
            // 循环封装CartProductVO
            for (Cart cartItem : cartList) {
                CartProductVO cartProductVO = new CartProductVO();
                cartProductVO.setId(cartItem.getId());
                cartProductVO.setUserId(cartItem.getUserId());
                cartProductVO.setProductChecked(cartItem.getChecked());

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if (product != null){
                    cartProductVO.setProductId(product.getId());
                    cartProductVO.setProductName(product.getName());
                    cartProductVO.setProductMainImage(product.getMainImage());
                    cartProductVO.setProductPrice(product.getPrice());
                    cartProductVO.setProductStock(product.getStock());
                    // 判断库存
                    int buyLimitCount = 0;
                    if (product.getStock() >= cartItem.getQuantity()){
                        buyLimitCount = cartItem.getQuantity();
                    }else {
                        // 不在库存范围之内，更改购物车中商品数量的为库存值
                        buyLimitCount = product.getStock();
                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setId(cartItem.getId());
                        cartForQuantity.setQuantity(buyLimitCount);
                        cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                    }
                    cartProductVO.setQuantity(buyLimitCount);
                    cartProductVO.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartItem.getQuantity()));
                }

                if (cartItem.getChecked() == Constants.Cart.CHECK){
                    tempProductTotalPrice = BigDecimalUtil.add(tempProductTotalPrice.doubleValue(),cartProductVO.getProductTotalPrice().doubleValue());
                }

                cartProductVOList.add(cartProductVO);
               
            }
        }

        cartListVO.setAllChecked(this.selectAllChecked(userId));
        cartListVO.setCartProductVOList(cartProductVOList);
        cartListVO.setCartTotalPrice(tempProductTotalPrice);
        cartListVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return cartListVO;
    }

    /**
     * 根据传入的userId查询是否有checked为0的商品
     * @param userId
     * @return
     */
    public boolean selectAllChecked(Integer userId){
        if (userId == null){
            return false;
        }
        return cartMapper.selectProductAllCheckedByuserId(userId) == 0;
    }

    /**
     * 选中或不选中商品
     * @param userId
     * @param productId
     * @param check
     * @return
     */
    @Override
    public Result selectOrUnSelect(Integer userId, Integer productId, Integer check) {
        int updateResult = cartMapper.selectOrUnSelect(userId,productId,check);
        if (updateResult > 0){
            this.cartList(userId);
            return ResultGenerator.getSuccessResult(ServiceResultEnum.SUCCESS.getResult());
        }
        return ResultGenerator.getFailResult(ServiceResultEnum.ERROR.getResult());
    }

    /**
     * 先判断传入的数据是否为空
     * 更新购物车数量，重新加载购物车信息
     * @param userId
     * @param newCount
     * @param productId
     * @return
     */
    @Override
    public Result updateCartProductCount(Integer userId, Integer newCount, Integer productId) {
        if (newCount == null || productId == null){
            return ResultGenerator.getFailResult(Constants.ILLEGAL_ARGUMENT);
        }
        int updateResult = cartMapper.updateQuantityByUserIdProductId(userId,newCount,productId);

        if (updateResult > 0){
            this.cartList(userId);
            return ResultGenerator.getSuccessResult("更新购物车成功！");
        }
        return ResultGenerator.getFailResult(ServiceResultEnum.ERROR.getResult());
    }

    /**
     * 删除单个商品和多个商品方法
     * @param userId
     * @param productIds
     * @return
     */
    @Override
    public Result deleteCartProductCount(Integer userId, String productIds) {
        List<String> productIdList = Arrays.asList(productIds.split(","));
        if (productIdList.isEmpty()){
            return ResultGenerator.getFailResult(Constants.ILLEGAL_ARGUMENT);
        }
        int deleteResult = cartMapper.deleteCartByUserIdProductId(userId,productIdList);
        if (deleteResult > 0){
            return ResultGenerator.getSuccessResult("删除商品成功！");
        }
        return ResultGenerator.getFailResult("删除商品失败！");
    }

    /**
     * 添加商品到购物车
     * @param cart
     * @return
     */
    @Override
    public Result cart_add(Cart cart) {
        if (cart == null){
            return ResultGenerator.getFailResult(Constants.ILLEGAL_ARGUMENT);
        }
        Cart cartIsExist = cartMapper.selectProductExist(cart.getUserId(), cart.getProductId());
        if (cartIsExist == null){
            Cart cartAdd = new Cart();
            cartAdd.setUserId(cart.getUserId());
            cartAdd.setProductId(cart.getProductId());
            cartAdd.setQuantity(cart.getQuantity());
            cartAdd.setChecked(Constants.CART_CHECKED);
            cartMapper.insert(cartAdd);
        }else {
            int count =  cartIsExist.getQuantity() + cart.getQuantity();
            cartIsExist.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cartIsExist);
        }
        return ResultGenerator.getSuccessResult("加入购物车成功");
    }

    /**
     * 查询购物车的商品种类数量
     * @param userId
     * @return
     */
    public int cart_count(Integer userId){
        return cartMapper.selectCartCountByUserId(userId);
    }
}
